import * as React from 'react';
import { Route, Redirect } from 'react-router-dom';

// interface GuardProps {
//     path:string;
//     component:React.Component;
//     permissions?:any[];
//     exact?:boolean|undefined;
//     strict?:boolean|undefined;
//     otherProps?:object;
// }




// 可以由mobx注入用户信息
class Guard extends React.Component<any, any> {
    constructor(props: any) {
        super(props);
        // 假设这里从 mobx 里面拿到了用户信息
        const userinfo = {
            level: 1 // 假设等级是一般用户
        };
        // 如果用户信息不存在，则需要去登录
        let auth = true;
        if (!userinfo) {
            auth = false;
        } else if (this.props.permissions) {
            // 如果存在，说明是需要区别等级鉴权的
            const permissions = this.props.permissions;
            if (permissions.indexOf(userinfo.level) === -1) {
                auth = false;
            }
        }
        this.state = {
            auth
        };
    }
    public render() {
        const ComponentPage = this.props.component;
        return (
            <Route
                path={this.props.path}
                exact={this.props.exact || false}
                strict={this.props.strict || false}
                render={props => {
                    return (
                        this.state.auth ? (
                            <ComponentPage {...props} {...this.props.otherProps} />
                        ) : (
                                <Redirect to={{
                                    pathname: '/login',
                                    state: { from: props.location }
                                }} />
                            )

                    )
                }
                }
            />
        );
    }
}
export default Guard;